package craky.componentc;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicPopupMenuUI;
import javax.swing.plaf.basic.DefaultMenuLayout;

import com.abigdreamer.swing.component.UIResourceManager;
import com.abigdreamer.swing.component.UIUtil;

public class CPopupMenuUI extends BasicPopupMenuUI {
	private PropertyChangeHandler propertyChangeListener;

	public static ComponentUI createUI(JComponent c) {
		return new CPopupMenuUI();
	}

	public void update(Graphics g, JComponent c) {
		boolean translucencySupported = UIUtil.isTranslucencySupported();
		Insets imageInsets = translucencySupported ? new Insets(9, 32, 9, 8) : new Insets(4, 27, 4, 3);
		Image image = UIResourceManager.getImage(translucencySupported ? "MenuBackgroundImage" : "MenuNoShadowBackgroundImage");
		UIUtil.paintImage(g, image, imageInsets, new Rectangle(0, 0, this.popupMenu.getWidth(), this.popupMenu.getHeight()), this.popupMenu);
		paint(g, c);
	}

	protected void installListeners() {
		super.installListeners();

		if (this.propertyChangeListener == null) {
			this.propertyChangeListener = new PropertyChangeHandler();
		}

		UIManager.addPropertyChangeListener(this.propertyChangeListener);
	}

	protected void uninstallListeners() {
		super.uninstallListeners();

		if (this.propertyChangeListener != null) {
			UIManager.removePropertyChangeListener(this.propertyChangeListener);
		}
	}

	public void installDefaults() {
		if ((this.popupMenu.getLayout() == null) || ((this.popupMenu.getLayout() instanceof UIResource))) {
			this.popupMenu.setLayout(new DefaultMenuLayout(this.popupMenu, 1));
		}
	}

	protected void uninstallDefaults() {
	}

	private class PropertyChangeHandler implements PropertyChangeListener {
		private PropertyChangeHandler() {
		}

		public void propertyChange(PropertyChangeEvent e) {
			if ("lookAndFeel".equalsIgnoreCase(e.getPropertyName())) {
				SwingUtilities.updateComponentTreeUI(CPopupMenuUI.this.popupMenu);
			}
		}
	}
}